<?php
/**
 * 商品管理接口
 */
namespace app\api\controller;

//use app\common\model\OrderModel;
use app\common\model\Goods as GoodsModel;
use think\Controller;
use think\Db;
//use think\Request;

class Goods extends Common
{
    public function _initialize()
    {
    }

    /**
     * 获取所有的自提点
     * @return json_array
     */
    public function getSinces()
    {
        $sinces = GoodsModel::getSinces();
        if ($sinces) {
            return returnJson(1, 'ok', $sinces);
        }
        return returnJson(0, 'no data');
    }

    /**
     * 获取商家商品通用配置
     * @return json_array
     */
    public function getCommonAttr()
    {
        $merchantId = session('merchant.merchant_id');
        if (!$merchantId) return returnJson(0, '未登录');

        $data = Db('zj_goods_common_attr')
            ->where('merchant_id', intval($merchantId))->order('id desc')->find();
        if ($data) {
            // 如果全部的值都为空，则直接返回
            $aNesFields = [
                'goods_max_count','express_model_id', 'todoor_model_id',
                'services','rent_period_types','since_sites','return_addrs'
            ];
            $bNotNull = FALSE;
            foreach ($aNesFields as $field) {
                if ( $data[$field] && $data[$field] != '-1') {
                    $bNotNull = TRUE;
                }
            }
            if (!$bNotNull) return returnJson(0, 'no data');

            //需要处理的字段 services, rent_period_types, since_sites, return_addrs
            $data['services'] && $data['services'] = explode(',', $data['services']);
            $data['rent_period_types'] && $data['rent_period_types'] = json_decode($data['rent_period_types'], TRUE);
            $data['since_sites'] && $data['since_sites'] = explode(',', $data['since_sites']);
            $data['return_addrs'] && $data['return_addrs'] = explode(',', $data['return_addrs']);
            unset($data['id'], $data['merchant_id']);
                //print_r($data);exit;
            return returnJson(1, 'ok', $data);
        }
        return returnJson(0, 'no data');
    }

    /**
     *  保存商家商品通用配置
     */
    public function saveCommonAttr()
    {
        //$merchantId = 51;
        $merchantId = session('merchant.merchant_id');
        if (!$merchantId) return returnJson(0, '未登录');

        // 接收参数
        $params = json_decode(input('data/s'), TRUE);
        if (!$params) return returnJson(0, '参数缺失');
        // 参数校验
        $aNesFields = [
            'goods_max_count','express_model_id', 'todoor_model_id',
            'services','rent_period_types','since_sites','return_addrs'
        ];
        foreach ($aNesFields as $field) {
            if ( !isset($params[$field]) ) {
                return returnJson(0, '参数错误');
            }
        }

        $data = [];
        $data['merchant_id'] = $merchantId; //商家ID
        $data['goods_max_count'] = (int)$params['goods_max_count']; // 每笔限租
        //$data['is_cert'] = (int)$params['is_cert']; // 是否实名认证

        // 服务标准 1免押金 2包邮 3.免赔 4上门 5自提 6随租随还
        $data['services'] = '';
        if (is_array($params['services']) && $params['services']) {
            $data['services'] = implode(',',$params['services']);
        }

        // 租赁周期
        $data['rent_period_types'] = '';
        if (is_array($params['rent_period_types']) && $params['rent_period_types']) {
            $data['rent_period_types'] = json_encode($params['rent_period_types']);
        }
        $data['express_model_id'] = (int)$params['express_model_id']; // 快递模板freight_id type=1
        $data['todoor_model_id']  = (int)$params['todoor_model_id']; // 上门模板freight_id type=2

        // 自提点since_id 多个用英文逗号拼接
        $data['since_sites'] = '';
        if (is_array($params['since_sites']) && $params['since_sites']) {
            //$data['since_sites'] = substr(implode(',',$params['since_sites']), 1);
            $data['since_sites'] = implode(',',$params['since_sites']);
        }

        // 归还地址 多个用英文逗号拼接
        $data['return_addrs'] = '';
        if (is_array($params['return_addrs']) && $params['return_addrs']) {
            $data['return_addrs'] = implode(',',$params['return_addrs']);
        }
        unset($params);

        // 查看商家是否保存过商品配置
        $count = $this->_count($merchantId);
        if (0 === intval($count)) {
            // 新增
            $res = Db('zj_goods_common_attr')->insert($data);
        }
        else {
            // 编辑
            $res = Db('zj_goods_common_attr')->where('merchant_id', intval($merchantId))->update($data);
        }
        return returnJson(1, '保存成功');
    }

    /**
     *  获取商家所有商品列表
     */
    public function getMerchantGoods()
    {
        $merchantId = session('merchant.merchant_id');
        if (!$merchantId) return returnJson(0, '未登录');

        $list = Db('goods')->alias('a')
            ->field('a.goods_id, a.goods_name, b.goods_main_pic')
            ->join('goods_main_img b', 'a.goods_id=b.goods_id', 'left')
            ->where('a.goods_merchant_id', $merchantId)
            ->where('goods_is_delete', 0)
            ->group('a.goods_id')
            ->order('a.goods_id desc')
            ->select();

        //echo count($list);exit;
        if ($list) {
            $path = config('goods_main_path');
            foreach ($list as & $val) {
                $val['goods_main_pic'] = $path . $val['goods_main_pic'];
            }
            unset($val);
            return returnJson(1, 'ok', $list);
        }
        return returnJson(0, 'no data');
    }

    /**
     *  批量更新商家商品续租折扣
     */
    public function batchUpdateDiscount() {

        //$merchantId = 51;
        $merchantId = session('merchant.merchant_id');
        if (!$merchantId) return returnJson(0, '未登录');

        // 接收参数
        $params = input('data/a');
        //print_r($params);exit；

        //if (!isset($params['goodsAttr']) || !isset($params['goodsList']) ) return returnJson(0, '参数缺失');
        if ( isset($params['goodsAttr']) && isset($params['goodsList'])
            && $params['goodsAttr'] && $params['goodsList'] )
        {
            // 校验goods_id 是否属于 该商家
            $goodsIds = Db('goods')->field('goods_id')
                ->where('goods_merchant_id', $merchantId)
                ->where('goods_is_delete', 0)
                ->select();
            if ($goodsIds){
                foreach ($goodsIds as $goodId) {
                    $ids[] = $goodId['goods_id'];
                }
                foreach ($params['goodsList'] as $key => $val){
                    if (!in_array($val, $ids)){
                        unset($params['goodsList'][$key]);
                    }
                }
            }
            if (!$params['goodsList']) return returnJson(0, '未更新');

            // 保存商家设置的信息
            $saveData['merchant_id'] = $merchantId;
            $saveData['goods_ids'] = implode(',',$params['goodsList']);
            $saveData['discount_str'] = json_encode($params['goodsAttr']);
            if (Db('zj_goods_updated_attr')->where('merchant_id',$merchantId)->count()){
                Db('zj_goods_updated_attr')->where('merchant_id',$merchantId)->update($saveData);
            }else{
                Db('zj_goods_updated_attr')->insert($saveData);
            }

            //[80,70,60,90,-1]   1-日 2-周 3-月 4-季 5-年 rent_period_type
            if (intval($params['goodsAttr'][0]) > 0){//日
                self::_updateReletPeriod($params, 1, 0);
            }
            if (intval($params['goodsAttr'][1]) > 0){//周
                self::_updateReletPeriod($params, 2, 1);
            }
            if (intval($params['goodsAttr'][2]) > 0){//月
                self::_updateReletPeriod($params, 3, 2);
            }
            if (intval($params['goodsAttr'][3]) > 0){//季
                self::_updateReletPeriod($params, 4, 3);
            }
            if (intval($params['goodsAttr'][4]) > 0){//年
                self::_updateReletPeriod($params, 5, 4);
            }
            return returnJson(1, '更新成功');
        }
        return returnJson(0, '未更新');
    }

    /**
     *  获取商家商品上次更新续租折扣属性
     */
    public function getUpdatedAttr()
    {
        $merchantId = session('merchant.merchant_id');
        if (!$merchantId) return returnJson(0, '未登录');
        $data = Db('zj_goods_updated_attr')->field('goods_ids, discount_str')->where('merchant_id', $merchantId)->find();
        if ($data) {
            $data['goods_ids'] = explode(',', $data['goods_ids']);
            $data['discount_str'] = json_decode($data['discount_str'], TRUE);
            return returnJson(1, 'ok', $data);
        }
        return returnJson(0, 'no data');
    }




    // ======================================
    // ============  私有方法   =============
    // ======================================

    /**
     *  检查商家商品公共属性配置是否存在
     */
    private function _count($merchantId)
    {
        return Db::name('zj_goods_common_attr')->where('merchant_id', intval($merchantId))->count();
    }

    /**
     *  更新续租折扣
     */
    private function _updateReletPeriod($params, $type, $key) {
        Db('rent_period')
            ->where('rent_period_goods_id', 'in', implode(',',$params['goodsList']))
            ->where('rent_period_type', $type)
            ->update(['relet_discount' => intval($params['goodsAttr'][$key])]);
    }




}
